import { _decorator, AudioClip, CCInteger, Component, director, Node, sys } from 'cc'
import { GameOverUI } from './UI/GameOverUI'
import { AudioMgr } from './AudioMgr'
const { ccclass, property } = _decorator

@ccclass('GameManager')
export class GameManager extends Component {
  static instance: GameManager
  static getInstance(): GameManager {
    if (!this.instance) {
      this.instance = new GameManager()
    }
    return this.instance
  }

  // 炸弹数量
  @property({ type: CCInteger })
  bombCount: number = 0

  // 分数
  @property({ type: CCInteger })
  score: number = 0

  // 暂停按钮
  @property({ type: Node })
  pauseButtonNode: Node = null

  // 继续按钮
  @property({ type: Node })
  resumeButtonNode: Node = null

  // 游戏结束
  @property({ type: GameOverUI })
  gameOverUI: GameOverUI = null

  // 最高分
  bestScore: number = 0

  // 游戏音乐
  @property({ type: AudioClip })
  gameMusic: AudioClip = null

  // 按钮点击声
  @property({ type: AudioClip })
  buttonClickSound: AudioClip = null

  // 游戏失败声
  @property({ type: AudioClip })
  gameOverSound: AudioClip = null

  start() {
    GameManager.instance = this
    this.getBestScore()
    AudioMgr.inst.play(this.gameMusic, 0.2)
  }

  update(deltaTime: number) {}

  addBomb() {
    if (this.bombCount < 3) {
      this.bombCount++
      this.node.emit('onBombCountChange', this.bombCount)
    }
  }
  minusBomb() {
    if (this.bombCount > 0) {
      this.bombCount--
      this.node.emit('onBombCountChange', this.bombCount)
    }
  }
  getBombNumber(): number {
    return this.bombCount
  }

  addScore(score: number) {
    this.score += score
    this.node.emit('onScoreChange', this.score)
  }
  onPauseButtonClick() {
    AudioMgr.inst.playOneShot(this.buttonClickSound, 1)
    AudioMgr.inst.pause()
    director.pause()
    this.pauseButtonNode.active = false
    this.resumeButtonNode.active = true
  }
  onResumeButtonClick() {
    AudioMgr.inst.playOneShot(this.buttonClickSound, 1)
    AudioMgr.inst.resume()
    director.resume()
    this.pauseButtonNode.active = true
    this.resumeButtonNode.active = false
  }
  restartButtonClick() {
    AudioMgr.inst.playOneShot(this.buttonClickSound, 1)
    this.onResumeButtonClick()
    director.loadScene(director.getScene().name)
  }
  quitButtonClick() {
    console.log('quitButtonClick')
    // director.loadScene('01-StartScene')
  }
  getBestScore() {
    const score = sys.localStorage.getItem('bestScore')
    if (!score) {
      this.bestScore = 0
    } else {
      this.bestScore = parseInt(score)
    }
  }
  gameOver() {
    AudioMgr.inst.playOneShot(this.gameOverSound, 1)
    if (this.bestScore < this.score) {
      this.bestScore = this.score
    }
    sys.localStorage.setItem('bestScore', this.bestScore)
    this.onPauseButtonClick()
    this.gameOverUI.showGameOverUI(this.bestScore, this.score)
  }
}
